package org.shijiagen.collect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.shijiagen.clients.ProductClient;
import org.shijiagen.collect.mapper.CollectMapper;
import org.shijiagen.collect.service.CollectService;
import org.shijiagen.param.ProductCollectParam;
import org.shijiagen.pojo.Collect;
import org.shijiagen.pojo.Product;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class CollectServiceImpl implements CollectService {

    private final CollectMapper collectMapper;

    private final ProductClient productClient;

    @Override
    public List<Product> list(Integer userId) {
        // 根据用户id获取用户收藏的商品id
        List<Object> productIds = collectMapper.selectObjs(new QueryWrapper<Collect>().select("product_id")
                .eq("user_id", userId));
        // 对获取到的商品id进行类型转换
        List<Integer> ids = productIds.stream().map(productId->(Integer)productId).toList();
        if(ids.isEmpty()){
           return new ArrayList<>();
        }
        // 创建参数对象
        ProductCollectParam productCollectParam = new ProductCollectParam();
        // 将查询到的对应的商品id传进参数对象中
        productCollectParam.setProductIds(ids);
        // 调用根据id查询商品详情方法
        return productClient.productListByIds(productCollectParam);
    }

    @Override
    public Boolean save(Collect collect) {
        // 查询收藏商品是否已经收藏
        Long totalNumber = collectMapper.selectCount(new QueryWrapper<Collect>().eq("user_id", collect.getUserId())
                .eq("product_id", collect.getProductId()));
        if(totalNumber != 0){
            return false;
        }
        // 如果没有收藏则收藏该商品并添加时间辍,如果影响行数大于零则代表收藏成功
        collect.setCollectTime(System.currentTimeMillis());
        return collectMapper.insert(collect) > 0;
    }

    @Override
    public Boolean remove(Collect collect) {
        return collectMapper.delete(new QueryWrapper<Collect>()
                .eq("product_id",collect.getProductId())
                .eq("user_id",collect.getUserId())) > 0;
    }

    @Override
    public boolean removeByPid(Integer productId) {
        return collectMapper.delete(new QueryWrapper<Collect>().eq("product_id",productId)) > 0;
    }
}
